package com.zbkj.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zbkj.client.dao.MaterialMapper;
import com.zbkj.client.service.MaterialService;
import com.zbkj.client.service.PieceService;
import com.zbkj.client.vo.FileResultVo;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.assets.Material;
import com.zbkj.common.model.client.workbench.IntoPieces;
import com.zbkj.common.model.client.workbench.VideoTemplateFinal;
import com.zbkj.common.request.client.MaterialAddRequest;
import com.zbkj.common.utils.OssUtil;
import com.zbkj.common.vo.client.CreateFolderVo;
import com.zbkj.common.vo.client.OssResponseVo;
import com.zbkj.service.service.IntoPiecesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
public class PieceServiceImpl implements PieceService {

    @Autowired
    private IntoPiecesService intoPiecesService;

    /**
     *    新建文件夹
     */
    @Override
    public boolean createFolder(CreateFolderVo vo) {
        Integer userId = vo.getUserId();
        Integer merId = vo.getMerId();
        Integer parentId = vo.getParentId() == null ? 0 : vo.getParentId();
        String name = vo.getName();

        // 新建文件夹：id为空
        IntoPieces intoPieces = new IntoPieces();
        intoPieces.setName(name);
        intoPieces.setParentId(parentId);
        intoPieces.setIsFolder(1);
        intoPieces.setIsDel(0);
        intoPieces.setUserId(userId);
        intoPieces.setMerId(merId);
        intoPieces.setCreateTime(new Date());
        intoPieces.setUpdateTime(new Date());
        // 处理completeFolder
        String completeFolder = "/";
        if (parentId != null && parentId != 0) {
            IntoPieces parent = intoPiecesService.getById(parentId);
            if (parent == null) throw new CrmebException("父级文件夹不存在");

            //TODO 4
            if (parent.getUserId() != userId) throw new CrmebException("您无权进行该操作");
            if (parent.getIsFolder() == 0) throw new CrmebException("不能移动到非文件夹下");

            completeFolder = parent.getCompleteFolder() + parent.getId() + "/";
        }
        intoPieces.setCompleteFolder(completeFolder);
        intoPiecesService.save(intoPieces);
        return true;
    }

    @Override
    public boolean renameFile(CreateFolderVo vo) {
        Integer userId = vo.getUserId();
        String name = vo.getName();
        Integer id = vo.getId();

        if(name == null || name.isEmpty()) throw new CrmebException("请输入要改的名字");
        if(id == null || id == 0) throw new CrmebException("请选择要改名的文件");

        IntoPieces intoPieces = intoPiecesService.getById(id);
        if (intoPieces == null) throw new CrmebException("要重命名的文件夹不存在");
        if (intoPieces.getUserId() != userId) throw new CrmebException("您无权进行该操作");

        intoPieces.setName(name);
        intoPieces.setUpdateTime(new Date());
        intoPiecesService.updateById(intoPieces);
        return true;
    }

    //移动文件夹
    @Override
    public boolean moveFolder(CreateFolderVo vo) {
        Integer userId = vo.getUserId();
        Integer merId = vo.getMerId();
        Integer parentId = vo.getParentId() == null ? 0 : vo.getParentId();

        Integer id = vo.getId();

        // 移动文件夹：name为空且parentId不为空且id不为空
        if(id == null) throw new CrmebException("请选择要移动的文件或者文件夹");

        IntoPieces folder = intoPiecesService.getById(id);
        if (folder == null) throw new CrmebException("要移动的文件夹不存在");
        //TODO 2
        if (folder.getUserId() != userId) throw new CrmebException("您无权进行该操作");

        String completeFolderOld = folder.getCompleteFolder();
        String oldPath = completeFolderOld + id + "/";

        // 新父级
        String completeFolder = "/";
        if (parentId != 0) {
            IntoPieces parent = intoPiecesService.getById(parentId);
            if (parent == null) throw new CrmebException("父级文件夹不存在");

            if (parent.getUserId() != userId) throw new CrmebException("您无权进行该操作");
            if (parent.getIsFolder() == 0) throw new CrmebException("请对文件夹进行操作");

            completeFolder = parent.getCompleteFolder() + parent.getId() + "/";
        }

        //TODO 3
        if (folder.getIsFolder() == 1){
            // 只有原文件是文件夹类型，才更新所有子文件夹和文件的complete_folder
            UpdateWrapper<IntoPieces> updateWrapper = new UpdateWrapper<>();
            updateWrapper.likeRight("complete_folder", oldPath);
            updateWrapper.setSql("complete_folder = CONCAT('" + completeFolder + id + "/', SUBSTRING(complete_folder, " + (oldPath.length() + 1) + "))");
            intoPiecesService.update(null, updateWrapper);
        }
        // 同时更新当前文件夹的parentId和complete_folder
        folder.setParentId(parentId);
        folder.setCompleteFolder(completeFolder);
        folder.setUpdateTime(new Date());
        intoPiecesService.updateById(folder);
        return true;
    }

    @Override
    public boolean batchMoveFolder(CreateFolderVo vo) {
        List<Integer> ids = vo.getIds();
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        Integer userId = vo.getUserId();
        Integer parentId = vo.getParentId();

        // 验证目标父级文件夹
        if (parentId != null && parentId != 0) {
            IntoPieces parent = intoPiecesService.getById(parentId);
            if (parent == null) {
                throw new CrmebException("目标父级文件夹不存在");
            }
            if (!userId.equals(parent.getUserId())) {
                throw new CrmebException("无权操作目标文件夹");
            }
            if (parent.getIsFolder() == null || parent.getIsFolder() == 0) {
                throw new CrmebException("目标必须是文件夹");
            }
        }

        String completeFolderNew = "/";
        if (parentId != null && parentId != 0) {
            IntoPieces parent = intoPiecesService.getById(parentId);
            completeFolderNew = parent.getCompleteFolder() + parent.getId() + "/";
        }

        for (Integer id : ids) {
            try {
                IntoPieces folder = intoPiecesService.getById(id);
                if (folder == null) {
                    throw new CrmebException("文件夹ID " + id + " 不存在");
                }
                if (!userId.equals(folder.getUserId())) {
                    throw new CrmebException("无权操作文件夹ID " + id);
                }

                String completeFolderOld = folder.getCompleteFolder();
                String oldPath = completeFolderOld + id + "/";

                if (folder.getIsFolder() == 1){
                    // 更新所有子文件夹和文件的complete_folder
                    UpdateWrapper<IntoPieces> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.likeRight("complete_folder", oldPath);
                    updateWrapper.setSql("complete_folder = CONCAT('" + completeFolderNew + id + "/', SUBSTRING(complete_folder, " + (oldPath.length() + 1) + "))");
                    intoPiecesService.update(null, updateWrapper);
                }

                // 更新当前文件夹
                folder.setParentId(parentId);
                folder.setCompleteFolder(completeFolderNew);
                folder.setUpdateTime(new Date());
                intoPiecesService.updateById(folder);

            } catch (Exception e) {
                throw new CrmebException("移动文件夹ID " + id + " 失败: " + e.getMessage());
            }
        }

        return true;
    }


    /**
     * 批量删除素材
     * @param ids
     * @return
     */
    @Override
    public boolean batchDelVideo(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        //要批量删除OSS文件，减少OSS删除文件的请求
        List<String> fileList = new ArrayList<>();

        for (Integer id : ids) {
            try {
                List<String> result = delVideo(id, fileList);
                fileList = result;
            } catch (Exception e) {
                // 记录错误但继续处理其他ID
                System.err.println("删除素材ID " + id + " 失败: " + e.getMessage());
            }
        }

        //这里调用OSS的批量删除接口
        log.info("要删除的文件为：{}", fileList);
        // 如果列表不为空，异步删除OSS文件
        if (!fileList.isEmpty()) {
            final List<String> finalFileList = fileList;
            CompletableFuture.runAsync(() -> {
                try {
                    OssUtil.deleteMultiFileFromUrls(finalFileList);
                    log.info("异步删除OSS文件成功: {}", finalFileList);
                } catch (Exception e) {
                    log.error("异步删除OSS文件失败: {}, 错误信息: {}", finalFileList, e.getMessage());
                }
            });
        }

        return true;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    private List<String> delVideo(Integer id, List<String> fileList) {
        IntoPieces intoPieces = intoPiecesService.getById(id);
        if (intoPieces == null) throw new CrmebException("素材不存在");
        // 判断是否为文件夹
        if (intoPieces.getIsFolder() != null && intoPieces.getIsFolder() == 1) {
            // 文件夹，删除所有子项
            String delFolderId = intoPieces.getCompleteFolder() + id + "/";
            UpdateWrapper<IntoPieces> updateWrapper = new UpdateWrapper<>();
            updateWrapper.likeRight("complete_folder", delFolderId);

            // 添加符合条件的is_folder=0记录的id到fileList
            List<IntoPieces> childItems = intoPiecesService.list(updateWrapper);
            for (IntoPieces childItem : childItems) {
                if (childItem.getIsFolder() != null && childItem.getIsFolder() == 0) {
                    if (childItem.getUrl() != null && !childItem.getUrl().isEmpty()) {
                        fileList.add(childItem.getUrl());
                    }
                }
            }

            updateWrapper.set("is_del", 1);
            intoPiecesService.update(null, updateWrapper);
        }else{
            if (intoPieces.getUrl() != null && !intoPieces.getUrl().isEmpty()) {
                fileList.add(intoPieces.getUrl());
            }
        }
        // 删除自身
        intoPieces.setIsDel(1);
        intoPieces.setUpdateTime(new Date());
        intoPiecesService.removeById(intoPieces);

        return fileList;
    }

    @Override
    public FileResultVo getFileResultVoById(Integer id, Integer userId) {
        IntoPieces intoPieces = intoPiecesService.getById(id);
        if (intoPieces == null || intoPieces.getIsDel() == null || intoPieces.getIsDel() != 0) {
            throw new CrmebException("成片文件不存在或已被删除");
        }
        if (!userId.equals(intoPieces.getUserId())) {
            throw new CrmebException("无权下载该素材文件");
        }
        if (intoPieces.getIsFolder() != null && intoPieces.getIsFolder() == 1) {
            throw new CrmebException("不能下载文件夹");
        }
        if (intoPieces.getUrl() == null || intoPieces.getUrl().isEmpty()) {
            throw new CrmebException("素材文件URL为空");
        }
        return new FileResultVo(intoPieces.getName(), intoPieces.getUrl());
    }
} 